package com.uxsino.commons.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

public class IPUtil {

    private static Logger logger = LoggerFactory.getLogger(IPUtil.class);

    private static final String LOCAL_HOST_IP = "127.0.0.1";

    /**
     * 根据网卡获得IP地址
     * @return
     * @throws SocketException
     * @throws UnknownHostException
     */
    public static String getIpAdd() throws SocketException, UnknownHostException {
        String ip = LOCAL_HOST_IP;
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            String name = intf.getName();
            if (!name.contains("docker") && !name.contains("lo")) {
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    // 获得IP
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipaddress = inetAddress.getHostAddress().toString();
                        if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                            logger.debug("IP:" + ipaddress);
                            if (!LOCAL_HOST_IP.equals(ipaddress)) {
                                ip = ipaddress;
                            }
                        }
                    }
                }
            }
        }
        return ip;
    }

    public static boolean isIPv4(String host) {
        Pattern p = Pattern.compile("^(\\d+\\.){3}\\d+$", Pattern.DOTALL);
        Matcher m = p.matcher(host);
        return m.matches();
    }

    public static InetAddress convertToInet4Addr(String ip) {
        String[] arr = ip.split("\\.");
        byte[] byteArr = new byte[4];
        for (int i = 0; i < byteArr.length; i++) {
            byteArr[i] = (byte) Integer.parseInt(arr[i]);
        }
        InetAddress addr = null;
        try {
            addr = InetAddress.getByAddress(byteArr);
        } catch (UnknownHostException e) {
            logger.error("failed to convert host {} to InetAddress", ip, e);
        }
        return addr;
    }

    /**
     * 获取http请求的网络地址
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    public static boolean isBroadcastAddr(String ipv4, String mask){
        String[] arr = ipv4.split("\\.");
        int[] byteIp = new int[4];
        for (int i = 0; i < byteIp.length; i++) {
            byteIp[i] = Integer.parseInt(arr[i]);
        }
        arr = mask.split("\\.");
        int[] byteMask = new int[4];
        for (int i = 0; i < byteMask.length; i++) {
            byteMask[i] = Integer.parseInt(arr[i]);
        }
        int[] ad = new int[4];

        for (int i = 0; i < byteIp.length; i++) {
            ad[i] = byteIp[i] | byteMask[i];
        }

        for (int b : ad) {
            System.out.println("ss"+b);
            if(b != 255){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isBroadcastAddr("192.168.1.255", "255.255.255.0"));
    }
}
